#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdlib.h>
#include <sys/wait.h>  // 新增必要头文件

#define DELAY_TIME 2

union semun {
    int val;
    struct semid_ds *buf;
    unsigned short *array;
};

int sem_p(int sem_id) {
    struct sembuf sem_b;
    sem_b.sem_num = 0;
    sem_b.sem_op = -1;
    sem_b.sem_flg = SEM_UNDO;
    return semop(sem_id, &sem_b, 1);
}

int sem_v(int sem_id) {
    struct sembuf sem_b;
    sem_b.sem_num = 0;
    sem_b.sem_op = 1;
    sem_b.sem_flg = SEM_UNDO;
    return semop(sem_id, &sem_b, 1);
}

int main(void) {
    pid_t pid;
    int sem_id;

    if ((sem_id = semget(ftok(".",'a'), 1, 0666|IPC_CREAT)) == -1) {
        perror("semget failed");
        exit(EXIT_FAILURE);
    }

    union semun sem_union;
    sem_union.val = 0;
    if (semctl(sem_id, 0, SETVAL, sem_union) == -1) {
        perror("semctl init failed");
        exit(EXIT_FAILURE);
    }

    pid = fork();
    if (pid < 0) {
        perror("fork failed");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        printf("Child process start\n");
        sleep(DELAY_TIME);
        printf("Child output: BBBBBBBBBB\n");
        sem_v(sem_id);
        exit(EXIT_SUCCESS);
    } else {
        sem_p(sem_id);
        printf("Parent output: AAAAAAAAAA\n");
        if (semctl(sem_id, 0, IPC_RMID) == -1) {
            perror("semctl delete failed");
        }
        wait(NULL);  // 正确定义
    }

    return 0;
}

